var origin = window.location.origin;

new Vue({
    el:'.main',
    data:{
        list : [],
        todo : ''
    },
    methods:{
        addList(){
            if(!this.todo.trim()){
                return;
            }
            $.ajax({
                url: origin + '/addList',
                type:'post',
                data:{
                    content : this.todo,
                    isFinished : 'false'
                },
                success:(res)=>{
                    this.list = this.list.concat(res.ops);
                    this.todo = '';
                },
                error:(err)=>{
                    console.log(err);
                }
            });
        },
        getList(){
            $.ajax({url : origin +'/getList',
                type: 'post',
                success :(res)=>{
                    this.list = res;
                },
                error:(err)=>{
                    console.log(err);
                }
            });
        },
        deleteList(ev){
            var id = ev.target.previousElementSibling.getAttribute('data-id');
            if(!id){
                return;
            }
            $.ajax({
                url : origin + '/deleteList',
                type: 'post',
                data : {
                    _id : id
                },
                success : (res)=>{
                    if(res.ok){
                        this.list = this.list.filter((val)=>{
                            return val._id != id;
                        });
                    }
                },
                error : (res)=>{
                    console.log(res);
                }
            });
        },
        updateState(ev){
            var target = ev.target;
            var id = target.nextElementSibling.getAttribute('data-id');
            if(!id){
                return;
            }
            var state ;
            this.list.forEach((val)=>{
                if(val._id == id){
                    state = val.isFinished;
                }
            });
            $.ajax({
                url : origin + '/updateState.js',
                type : 'post',
                data :{
                    _id : id,
                    isFinished : state + ''
                },
                success : (res)=>{
                    
                },
                error : (res)=>{
                    console.log(res);
                }
            });
        }
    },
    beforeMount(){
        this.getList();
    }
});